// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event)
  switch (event.action) {
    case 'roundInfo': {
      return requestRoundInfo(event)
    }
    case 'postRoundResult': {
      return postRoundResult(event)
    }
    default: {
      return {
        code: 2,
        msg: 'action不可用',
        data: {}
      };
    }
  }
}

async function requestRoundInfo(event) {
  const wxContext = cloud.getWXContext();
  let openid = wxContext.OPENID;
  const db = cloud.database();
  try {
    let userResult = await db.collection('users').where({
      openid: openid,
    }).get();
    console.log(userResult);
    if (userResult.data.length == 0) {
      return {
        code: 1,
        msg: '用户不存在',
        data: {}
      };
    }

    let now = new Date();
    let activityResult = await db.collection('bless_activities').where({
      beginTime: db.command.lte(now),
      endTime: db.command.gte(now),
    }).get();
    console.log(activityResult);
    if (activityResult.data.length <= 0) {
      return {
        code: 1,
        msg: '当前没有活动',
        data: {}
      };
    }

    let activityId = activityResult.data[0]._id;
    let beginTime = activityResult.data[0].beginTime;
    let endTime = activityResult.data[0].endTime;

    let recordResult = await db.collection('bless_records').where({
      openid: openid,
      activityId: activityId,
    }).get();
    console.log(recordResult);
    if (recordResult.data.length > 0) {
      return {
        code: 0,
        msg: '查询成功',
        data: {
          activity: activityId,
          beginTime: beginTime,
          endTime: endTime,
          blessResult: {
            words: recordResult.data[0].words,
            seq: recordResult.data[0].seq,
          }
        }
      };
    } else {
      return {
        code: 0,
        msg: '查询成功',
        data: {
          activity: activityId,
          beginTime: beginTime,
          endTime: endTime,
          blessResult: {}
        }
      };
    }
  } catch (e) {
    console.log('bless round info catch exception openid ' + openid + ' err ' + e);
    return {
      code: 1,
      msg: 'error',
      data: {}
    }
  }
}

async function postRoundResult(event) {
  const wxContext = cloud.getWXContext();
  let openid = wxContext.OPENID;
  const db = cloud.database();
  try {
    let userResult = await db.collection('users').where({
      openid: openid,
    }).get();
    console.log(userResult);
    if (userResult.data.length == 0) {
      return {
        code: 1,
        msg: '用户不存在',
        data: {}
      };
    }

    let now = new Date();
    let activityId = event.activity;
    let words = event.words;

    let recordResult = await db.collection('bless_records').where({
      openid: openid,
      activityId: activityId,
    }).get();
    console.log(recordResult);
    if (recordResult.data.length > 0) {
      return {
        code: 1,
        msg: '之前祈福过',
        data: {
          activity: activityId,
          beginTime: beginTime,
          endTime: endTime,
          blessResult: {
            words: recordResult.data[0].words,
            seq: recordResult.data[0].seq,
          }
        }
      };
    }

    const transactionResult = await db.runTransaction(async transaction => {
      let updateResult = await db.collection('bless_activities').where({
        _id: activityId,
      }).update({
        data: {
          blessCount: db.command.inc(1),
        }
      });
      console.log(updateResult);

      let activityResult = await db.collection('bless_activities').where({
        _id: activityId,
      }).get();
      console.log(activityResult);
      if (activityResult.data.length <= 0) {
        return {
          code: 1,
          msg: '活动不存在',
          data: {}
        };
      }

      let seq = activityResult.data[0].blessCount;

      let addResult = await db.collection('bless_records').add({
        data: {
          openid: openid,
          activityId: activityId,
          words: words,
          seq: seq,
          createdAt: new Date(),
        }
      });
      console.log(addResult);
      return {
        code: 0,
        msg: '祈福成功',
        data: {
          activity: activityId,
          blessResult: {
            words: words,
            seq: seq,
          }
        }
      };
    });
  } catch (e) {
    console.log('bless round post catch exception openid ' + openid + ' err ' + e);
    return {
      code: 1,
      msg: 'error',
      data: {}
    }
  }
}